//
//  NetEngine.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/5/27.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

class NetEngine: NSObject {
    
    static let shared = NetEngine()
    
    /// 查询焦点，全体静音等消息
    /// - Parameters:
    ///   - ownid: 房间号
    ///   - focusID: 查询ID
    ///   - success: 成功后回调
    ///   - fail: 失败后回调
    class func respose_MeetStutas(roomId :String,success:ResultSuccess_obj?=nil,fail:ResultFail? = nil){
        let params:[String:Any] = ["ownid":roomId]
        NetworkTool.shared.postRequest(urlString: mt_url_findfocus, params: params, success: { (result) in
            let code = result["code"] as? Int
            if code != nil {
                switch code! {
                case 0:
                    if success != nil {
                        success!(result)
                    }
                default:
                    let msg = result["msg"] as? String ?? "code返回不成功"
                    show_msg(msg)
                    if fail != nil {
                        fail!(code ?? 10000,msg)
                    }
                }
            }
        }) { (error) in
            showNETFail()
        }
    }
    
    /// 设置焦点云端
    /// - Parameters:
    ///   - ownid: 房间号
    ///   - focusID: 焦点ID
    ///   - success: 成功后回调
    class func respose_SetFocus(ownid:String,focusID:String,success:ResultNo? = nil,fail:ResultNo? = nil ) {
        let params:[String:Any] = ["ownid":ownid,"focusid":focusID]
        NetworkTool.shared.postRequest(urlString: mt_url_addfocus, params: params, success: { (result) in
            let code = result["code"] as? Int
            if code != nil {
                switch code! {
                case 0:
                    success!()
                default:
                    let msg = result["msg"] as? String ?? "设置失败"
                    show_msg(msg)
                    fail!()
                }
            }
        }) { (error) in
            showNETFail()
        }
    }
    
    /// 是否支持共享
    /// - Parameters:
    ///   - ownid: 房间号
    ///   - isOk: is_share是否共享0是共享1是不共享
    ///   - success: 成功后回调
    ///   - fail: 失败后回调
    class func respose_Isshare(ownid:String,isOk:Bool,success:ResultNo? = nil,fail:ResultNo? = nil ) {
        let ok = isOk ? "0":"1"
        let params:[String:Any] = ["ownid":ownid,"is_share":ok]
        NetworkTool.shared.postRequest(urlString: mt_url_addshare, params: params, success: { (result) in
            let code = result["code"] as? Int
            if code != nil {
                switch code! {
                case 0:
                    success!()
                default:
                    let msg = result["msg"] as? String ?? "设置失败"
                    show_msg(msg)
                    fail!()
                }
            }
        }) { (error) in
            showNETFail()
        }
    }
    

    
    /// 是否支持聊天
    /// - Parameters:
    ///   - ownid: 房间号
    ///   - isOk: is_silent聊天开启 0开启1关闭
    ///   - success: 成功后回调
    ///   - fail: 失败后回调
    class func respose_Issilent(ownid:String,isOk:Bool,success:ResultNo? = nil,fail:ResultNo? = nil ) {
        let ok = isOk ? "0":"1"
        let params:[String:Any] = ["ownid":ownid,"is_silent":ok]
        NetworkTool.shared.postRequest(urlString: mt_url_addsilent, params: params, success: { (result) in
            let code = result["code"] as? Int
            if code != nil {
                switch code! {
                case 0:
                    success!()
                default:
                    let msg = result["msg"] as? String ?? "设置失败"
                    show_msg(msg)
                    fail!()
                }
            }
        }) { (error) in
            showNETFail()
        }
    }
    
    
    /// 是否支持上麦
    /// - Parameters:
    ///   - ownid: 房间号
    ///   - isOk: is_mike关闭上麦，0是不关闭
    ///   - success: 成功后回调
    ///   - fail: 失败后回调
    class func respose_Ismike(ownid:String,isOk:Bool,success:ResultNo? = nil,fail:ResultNo? = nil ) {
        let ok = isOk ? "0":"1"
        let params:[String:Any] = ["ownid":ownid,"is_mike":ok]
        NetworkTool.shared.postRequest(urlString: mt_url_addmike, params: params, success: { (result) in
            let code = result["code"] as? Int
            if code != nil {
                switch code! {
                case 0:
                    success!()
                default:
                    let msg = result["msg"] as? String ?? "设置失败"
                    show_msg(msg)
                    fail!()
                }
            }
        }) { (error) in
            showNETFail()
        }
    }
    
    
    /// 是否全体静音
    /// - Parameters:
    ///   - ownid: 房间号
    ///   - isOk: is_speak会议室是否禁言，1不禁言，2禁言
    ///   - success: 成功后回调
    ///   - fail: 失败后回调
    class func respose_Isspeak(ownid:String,isOk:Bool,success:ResultNo? = nil,fail:ResultNo? = nil ) {
        let ok = isOk ? "2":"1"
        let params:[String:Any] = ["ownid":ownid,"is_speak":ok]
        NetworkTool.shared.postRequest(urlString: mt_url_addspeak, params: params, success: { (result) in
            let code = result["code"] as? Int
            if code != nil {
                switch code! {
                case 0:
                    success!()
                default:
                    let msg = result["msg"] as? String ?? "设置失败"
                    show_msg(msg)
                    fail!()
                }
            }
            
        }) { (error) in
            showNETFail()
        }
    }
    
    
    
    /// 获取会议号
    /// - Parameters:
    ///   - machineId: 设备ID
    ///   - success: 成功后回调
    ///   - fail: 失败后回调
    class func respose_getMeetingNum(ownidKey:String,success:ResultSuccess_obj? = nil,fail:ResultNo? = nil) {
        let params:[String:Any] = ["wifiId":ownidKey]
        NetworkTool.shared.postRequest(urlString: mt_url_getMeetingNum, params: params, success: { (result) in
            let code = result["code"] as? Int
            if code != nil {
                switch code! {
                case 0:
                    if success != nil {
                        success!(result)
                    }
                default:
                    let msg = result["msg"] as? String ?? "code=0"
                    GToast.show(msg: msg)
                    if fail != nil {
                        fail!()
                    }
                }
            }
            
        }) { (error) in
            Hud.dismiss()
            showNETFail()
        }
    }
    
    
    
    
    class func accessToken(ownid:String=UserInfoManager.shared.ownid!,seccess:((String)->())?=nil) {
        let params = ["plaintext":ownid]
        NetworkTool.requestData(type: MethodType.post, URLString: mt_url_accessToken, parameters: params, finishCallback: { (result) in
            if let dict = result as? [String:Any] {
                if let data = dict["data"] as? [String:Any] {
                    if let ciphertext = data["ciphertext"] as? String {
                        if seccess != nil {
                            seccess!(ciphertext)
                        }
                    }
                }
            }
            
        }) { (error) in
            
        }
        
    }
    
    class func getHostInfo(wifiId:String,success:((MeetingMode?)->())?=nil){
        
        Hud.show()
        let params:[String:Any] = ["machineId":wifiId, "wifiId":wifiId,"networkId":"", "type":"6","version":AppInfo.majorVersion()]
        
        NetworkTool.requestData(type: MethodType.post, URLString:  mt_url_config, parameters: params ,finishCallback: { (result) in
            Hud.dismiss()
            let mode = MeetingMode.deserialize(from: result as? [String:Any])
            guard let roomId = mode?.ownid else {
                return
            }
            switch mode?.code {
            case 0:
                NetEngine.getUserSig(userId: roomId, roomId: roomId) { (res) in
                    let usersig = res!["usersig"] as? String
                    mode?.usersig = usersig
                    if success != nil {
                        success!(mode)
                    }
                }
            default:
               GToast.show(msg: (mode?.msg)!)
            }
        }) { (error) in
            Hud.dismiss()
            GToast.show(msg: "获取数据失败，请稍后刷新重试".localized())
        }
        
    }
    
    /**
     获取UserSig
     - parameter userId:  userId
     - parameter roomId:  roomId
     - parameter success: success
     */
    class func getUserSig(userId: String,roomId: String,success:ResultSuccess?=nil) {

        let params:[String:Any] = ["userid":userId,"roomid":roomId]
        NetworkTool.requestData(type: .post, URLString: mt_url_usersig, parameters: params, finishCallback: { (result) in
            if success != nil {
                success!(result as? [String:Any])
            }
           
        }) { (error) in
           Hud.dismiss()
           GToast.show(msg: "获取Usersig失败，请联系开发人员".localized())
        }
    }
    
    
    
    class func getMeetingLive(ownid:String,roomid:String,push:OnePushType,success:ResultSuccess?=nil) {
        let type = (push == .live) ? "live":"record"
        let params:[String : String]? = ["type":type,"ownid":ownid,"roomid":roomid]
        NetworkTool.requestData(type: .post, URLString:  mt_url_push, parameters: params!, finishCallback: { (result) in
           let mode = RtmpMode.deserialize(from: result as? [String:Any])
           switch mode?.code {
           case 0:
               if success != nil {
                   success!(result as? [String : Any])
               }
           default:
               break
           }
        }) { (error) in
          
        }
    }


    class func getHostMeetingStatus(roomId: String, scene:String,success:ResultSuccess?=nil,last:ResultLast?=nil) {
        
         let params:[String : String]? = ["roomid":roomId,"scene":scene]
         NetworkTool.requestData(type: .post, URLString:  mt_url_hostInfo, parameters: params!, finishCallback: { (result) in
            let mode = HostMode.deserialize(from: result as? [String:Any])
            switch mode?.code {
            case 0:
                if success != nil {
                    success!(result as? [String:Any])
                }
            case 2:
                if last != nil {
                    last!(result as? [String:Any])
                }
            default:
                break
            }
         }) { (error) in
           
         }
    }


    class func getJoinMeetingStatus(roomId:String, userid: String,success:ResultSuccess?=nil,fail:ResultFail?=nil,passwrodResult:ResultSuccess?=nil) {
        
         let params:[String : String]? = ["roomid":roomId,"userid":userid];
         NetworkTool.requestData(type: .post, URLString:  mt_url_joinInfo, parameters: params!, finishCallback: { (result) in
            let mode = HostMode.deserialize(from: result as? [String:Any])
            switch mode?.code {
            case 0:
                if mode!.password != nil && mode?.password != ""{
                    if passwrodResult != nil {
                        passwrodResult!(result as? [String:Any])
                    }
                }else {
                    if success != nil {
                        success!(result as? [String:Any])
                    }
                }
                
            default:
                if fail != nil {
                    fail!(1,mode?.msg ?? "入会失败")
                }
                break
            }
            
         }) { (error) in
            
         }
    }
    
    class func requstAnnouce(success:ResultSuccess?=nil,fail:ResultFail?=nil) {
        let params:[String:Any] = ["version":AppInfo.majorVersion(),"type":"mac"]
        NetworkTool.requestData(type: .post, URLString: mt_url_announce, parameters: params, finishCallback: { (result) in
            if let dict = result as? [String:Any] {
                if let code = dict["code"] as? NSNumber {
                    if code == 0 {
                        if let dataRuselt = dict["data"] as? [String:Any] {
                            if success != nil {
                                success!(dataRuselt)
                            }
                        }
                    }else {
                        if fail != nil {
                            let msg = dict["msg"] as? String ?? ""
                            fail!(Int(truncating: code),msg)
                        }
                    }
                }
            }
        }) { (error) in
            
        }
    }
    
    class func requstCloseRoom(roomId:String,success:ResultSuccess_obj?=nil) {
        let params:[String : String]? = ["roomid":roomId];
        NetworkTool.requestData(type: .post, URLString:  mt_url_checkwxmeeting, parameters: params!, finishCallback: { (result) in
            let resultDic = (result as! [String:AnyObject])
            let code =  resultDic["code"] as! Int
            switch code {
            case 0:
                //获取结果做处理
                if success != nil {
                    success!(resultDic)
                }
            default:
                print("阻止会议失败")
            }
            
        }) { (error) in
            showNETFail()
        }
    }
    
    class func requseExitRoom(roomId:String,success:ResultSuccess_obj?=nil) {
        
        let params:[String : String]? = ["roomid":roomId];
        NetworkTool.requestData(type: .post, URLString:  mt_url_exitRoom, parameters: params!, finishCallback: { (result) in
            let resultDic = (result as! [String:AnyObject])
            let code =  resultDic["code"] as! Int
            switch code {
            case 0:
                //获取结果做处理
                if success != nil {
                    success!(resultDic)
                }
            default:
                print("阻止会议失败")
            }
            
        }) { (error) in
            showNETFail()
        }
    }
    
    class func requseTrtcExitRoom(roomId:String,success:ResultSuccess_obj?=nil) {
        
        let params:[String : String]? = ["roomid":roomId];
        NetworkTool.requestData(type: .get, URLString:  mt_url_trtcExitRoom, parameters: params!, finishCallback: { (result) in
            let resultDic = (result as! [String:AnyObject])
            let code =  resultDic["code"] as! Int
            switch code {
            case 0:
                //获取结果做处理
                if success != nil {
                    success!(resultDic)
                }
            default:
                print("阻止会议失败")
            }
            
        }) { (error) in
            showNETFail()
        }
    }
    
    class func requseImDetoryGroup(roomId:String,success:ResultSuccess_obj?=nil) {
        
        let params:[String : String]? = ["roomid":roomId];
        NetworkTool.requestData(type: .get, URLString:  mt_url_imDetoryGroup, parameters: params!, finishCallback: { (result) in
            let resultDic = (result as! [String:AnyObject])
            let code = resultDic["code"] as! Int
            switch code {
            case 0:
                //获取结果做处理
                if success != nil {
                    success!(resultDic)
                }
            default:
                print("阻止会议失败")
            }
            
        }) { (error) in
            showNETFail()
        }
    }
    
    class func requseLastExitRoom(roomId:String,success:ResultNo?=nil) {
        let group = DispatchGroup()
        /*
        DispatchQueue.global().async(group: group, execute: DispatchWorkItem.init(block: {
            NetEngine.requseTrtcExitRoom(roomId: roomId) { (result) in
                
            }
        }))
        DispatchQueue.global().async(group: group, execute: DispatchWorkItem.init(block: {
            NetEngine.requseImDetoryGroup(roomId: roomId) { (result) in
                
            }
        }))
        */
        
        DispatchQueue.global().async(group: group, execute: DispatchWorkItem.init(block: {
            NetEngine.requseExitRoom(roomId: roomId) { (result) in
                
            }
        }))
        group.notify(queue: DispatchQueue.main) {
            if success != nil {
                success!()
            }
        }
        
    }
    
    class func reponse_updateSetup(ownid:String,fieldType:UpSetupType,value:String,success: ResultSuccess?=nil,fail:ResultFail?=nil) {
        var field:String = ""
        switch fieldType {
        case .name:
            field = "name"
        case .password:
            field = "code"
        case .theme:
            field = "title"
        case .start_time:
            field = "start_time"
        case .mode:
            field = "mode"
        }
        
        let params :[String:Any] = [
            "ownid":ownid,
            "field":field,
            "value":value
        ]
        
        NetworkTool.requestData(type: .post, URLString:  mt_url_updateSetup, parameters: params, finishCallback: { (result) in
            if let dict = result as? [String:Any] {
                if let code = dict["code"] as? Int {
                    switch code {
                    case 0:
                        if success != nil {
                            success!(dict)
                        }
                    default:
                        if fail != nil {
                            let mssage = (dict["msg"] as? String) ?? "code!=0"
                            fail!(code,mssage)
                        }
                    }
                }
            }
        }) { (error) in
            showNETFail()
        }
    }
}

enum UpSetupType {
    case name
    case password
    case theme
    case start_time
    case mode
}


//MARK: - 壹会网获取
extension NetEngine {
    
    /// 获取会议号
    /// - Parameters:
    ///   - machineId: 设备ID
    ///   - success: 成功后回调
    ///   - fail: 失败后回调
    class func respose_getOneMeetingNum(ownidKey:String,success:ResultSuccess_obj? = nil,fail:ResultNo? = nil) {
        let params:[String:Any] = ["wifiId":ownidKey]
        NetworkTool.shared.postRequest(urlString: mt_url_getOneMeetingNum, params: params, success: { (result) in
            let code = result["code"] as? Int
            if code != nil {
                switch code! {
                case 0:
                    if success != nil {
                        success!(result)
                    }
                default:
                    let msg = result["msg"] as? String ?? "code=0"
                    GToast.show(msg: msg)
                    if fail != nil {
                        fail!()
                    }
                }
            }
            
        }) { (error) in
            Hud.dismiss()
            showNETFail()
        }
    }
}
